/**
 * @name MessageView
 * @author darcrand
 * @desc 聊天显示框
 */

import React, { Component } from 'react'
import { inject, observer } from 'mobx-react'
import moment from 'moment'
import Scrollbar from 'smooth-scrollbar'
import { Avatar } from '@/components'

import styles from './styles.module.less'

/**
 * @property {Object[]} messages
 * @property {Object} messages[].user
 * @property {String} messages[].user.id
 * @property {String} messages[].user.name
 * @property {String} messages[].user.avatar
 *
 * @property {String} messages[].message
 * @property {Number} messages[].date
 * @property {Boolean} messages[].isSelf
 * @property {Boolean} messages[].shouldShowDate
 */
@inject('UserStore')
@observer
class MessageView extends Component {
  static defaultProps = {
    messages: []
  }

  refScroll = React.createRef()
  scrollIns = null
  scrollTimer = null

  componentDidMount() {
    this.scrollIns = Scrollbar.init(this.refScroll.current)
  }

  componentDidUpdate(prevProps) {
    if (prevProps.messages.length !== this.props.messages.length && this.scrollIns) {
      clearTimeout(this.scrollTimer)
      this.scrollTimer = setTimeout(() => {
        const {
          content: { height }
        } = this.scrollIns.getSize()
        this.scrollIns.scrollTo(0, height, 200)
      }, 200)
    }
  }

  componentWillUnmount() {
    this.scrollIns && this.scrollIns.destroy()
  }

  render() {
    return (
      <div ref={this.refScroll} className={styles.container}>
        <ul>
          {this.props.messages.map(v => (
            <li key={v.date} className={styles.item}>
              {v.shouldShowDate && <p className={styles.date}>{moment(v.date).format('YYYY-MM-DD HH:mm:ss')}</p>}
              <div
                className={v.isSelf ? `${styles['content-wrapper']} ${styles['reverse']}` : styles['content-wrapper']}
              >
                <Avatar src={v.user.avatar} size="60px" type="square" />
                <div className={styles.info}>
                  <p className={styles.name}>{v.user.name}</p>
                  <p className={styles.content}>{v.message}</p>
                </div>
              </div>
            </li>
          ))}
        </ul>
      </div>
    )
  }
}

export default MessageView
